import {message} from 'antd'
import moment from 'moment';
import * as Md5Util from './md5Util';

moment.locale('zh-cn', {
    months: '一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月'.split('_'),
    monthsShort: '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'),
    weekdays: '星期日_星期一_星期二_星期三_星期四_星期五_星期六'.split('_'),
    weekdaysShort: '周日_周一_周二_周三_周四_周五_周六'.split('_'),
    weekdaysMin: '日_一_二_三_四_五_六'.split('_'),
    longDateFormat: {
        LT: 'Ah点mm分',
        LTS: 'Ah点m分s秒',
        L: 'YYYY-MM-DD',
        LL: 'YYYY年MMMD日',
        LLL: 'YYYY年MMMD日Ah点mm分',
        LLLL: 'YYYY年MMMD日ddddAh点mm分',
        l: 'YYYY-MM-DD',
        ll: 'YYYY年MMMD日',
        lll: 'YYYY年MMMD日Ah点mm分',
        llll: 'YYYY年MMMD日ddddAh点mm分'
    },
    meridiemParse: /凌晨|早上|上午|中午|下午|晚上/,
    meridiemHour: function (hour, meridiem) {
        if (hour === 12) {
            hour = 0;
        }
        if (meridiem === '凌晨' || meridiem === '早上' ||
            meridiem === '上午') {
            return hour;
        } else if (meridiem === '下午' || meridiem === '晚上') {
            return hour + 12;
        } else {
            // '中午'
            return hour >= 11 ? hour : hour + 12;
        }
    },
    meridiem: function (hour, minute, isLower) {
        var hm = hour * 100 + minute;
        if (hm < 600) {
            return '凌晨';
        } else if (hm < 900) {
            return '早上';
        } else if (hm < 1130) {
            return '上午';
        } else if (hm < 1230) {
            return '中午';
        } else if (hm < 1800) {
            return '下午';
        } else {
            return '晚上';
        }
    },
    calendar: {
        sameDay: function () {
            return this.minutes() === 0 ? '[今天]Ah[点整]' : '[今天]LT';
        },
        nextDay: function () {
            return this.minutes() === 0 ? '[明天]Ah[点整]' : '[明天]LT';
        },
        lastDay: function () {
            return this.minutes() === 0 ? '[昨天]Ah[点整]' : '[昨天]LT';
        },
        nextWeek: function () {
            var startOfWeek, prefix;
            startOfWeek = moment().startOf('week');
            prefix = this.unix() - startOfWeek.unix() >= 7 * 24 * 3600 ? '[下]' : '[本]';
            return this.minutes() === 0 ? prefix + 'dddAh点整' : prefix + 'dddAh点mm';
        },
        lastWeek: function () {
            var startOfWeek, prefix;
            startOfWeek = moment().startOf('week');
            prefix = this.unix() < startOfWeek.unix() ? '[上]' : '[本]';
            return this.minutes() === 0 ? prefix + 'dddAh点整' : prefix + 'dddAh点mm';
        },
        sameElse: 'LL'
    },
    ordinalParse: /\d{1,2}(日|月|周)/,
    ordinal: function (number, period) {
        switch (period) {
            case 'd':
            case 'D':
            case 'DDD':
                return number + '日';
            case 'M':
                return number + '月';
            case 'w':
            case 'W':
                return number + '周';
            default:
                return number;
        }
    },
    relativeTime: {
        future: '%s内',
        past: '%s前',
        s: '几秒',
        m: '1分钟',
        mm: '%d分钟',
        h: '1小时',
        hh: '%d小时',
        d: '1天',
        dd: '%d天',
        M: '1个月',
        MM: '%d个月',
        y: '1年',
        yy: '%d年'
    },
    week: {
        // GB/T 7408-1994《数据元和交换格式·信息交换·日期和时间表示法》与ISO 8601:1988等效
        dow: 1, // Monday is the first day of the week.
        doy: 4  // The week that contains Jan 4th is the first week of the year.
    }
});

message.config({
    top: 150,
    duration: 2,
});

export default class CommonUtil {
    static toast(msg) {
        if(!msg) return;
        if(typeof(msg) !== 'string' ) msg = JSON.stringify(msg);
        message.info(msg, 3, null);
    }

    static showLoading(msg = '正在加载，请稍候...') {
        message.loading(msg, 0, null);
    }

    static hideLoading() {
        message.destroy();
    }

    static parseTime(t, fmt = 'YYYY-MM-DD HH:mm:ss') {
        if(!t) return '';
        return moment(t).format(fmt);
    }

    static now(fmt = 'YYYY-MM-DD HH:mm:ss') {
        return moment().format(fmt);
    }

    static rdmFlowNo = () => {
        return CommonUtil.now('YYYYMMDDHHmmss') + Math.floor(Math.random() * 100000);
    };

    static genSign = (_rdm) => {
        return Md5Util.hex_md5(_rdm + 'ytmd@2018-wjchang')
    };

    static arrayToTree = (array, id = 'id', pid = 'pid', children = 'children') => {
        id = id || 'id';
        pid = pid || 'pid';
        children = children || 'children';

        let data = array;

        data = data.map(m=>{
            m[id] = String(m[id]);
            m[pid] = String(m[pid]);
            if(m[pid]==='0') {
                delete m[pid];
            }
            return m;
        });

        let result = [];
        let hash = {};
        data.forEach((item, index) => {
            hash[data[index][id]] = data[index]
        });

        data.forEach((item) => {
            let hashVP = hash[item[pid]];

            if (hashVP) {
                !hashVP[children] && (hashVP[children] = []);
                hashVP[children].push(item)
            } else {
                result.push(item)
            }
        });
        return result
    };

    static sliceArray(array, size, emptyAppend = false) {
        if(!array) return [[]];

        if (!Array.isArray(size)) {
            size = [size];
        }
        let result = [];

        let start = 0;
        let end = 0;

        while (end < array.length) {
            for (let s = 0; s < size.length; s++) {
                end = size[s] + start;
                if (end < array.length) {
                    result.push(array.slice(start, end));
                    start = end;
                } else {
                    let slices = array.slice(start, array.length);
                    slices.forEach(s=>{s.emptyAppend=false})
                    if (emptyAppend) {
                        for (let i = 0; i < end - array.length; i++) {
                            slices.push({emptyAppend: true})
                        }
                    }

                    result.push(slices);

                    break;
                }
            }
        }
        return result;
    }

    static getQueryString(name, search) {
        name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
        let regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
        let results = regex.exec(search);
        return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
    }

    static windowScrollTop(top = 0) {
        window.scrollTo(0, top);
    }

    static getExtType(file, hasDot = false) {
        let xp = file.lastIndexOf('.');
        return hasDot ? file.substring(xp, file.length).toLowerCase() : file.substring(xp + 1, file.length).toLowerCase();
    }

    static getFileName(file) {
        let xp = file.lastIndexOf('/');
        return file.substring(xp + 1, file.length).toLowerCase();
    }

    static fileType(filename) {
        let ext = this.getExtType(filename, true);
        if (!!~'.jpg,.jpeg,.png'.indexOf(ext)) {
            return 1;
        } else if (!!~'.mp3,.aac,.wav'.indexOf(ext)) {
            return 3;
        } else if (!!~'.avi,.wmv,.mpeg,.mp4,.mov,.mkv,.flv,.f4v,.m4v,.rmvb,.rm,.3gp,.dat,.ts,.mts,.vob'.indexOf(ext)) {
            return 2;
        } else if (!!~'.svg'.indexOf(ext)) {
            return 4;
        }
    }

    static formatMoney(number, places, symbol, thousand, decimal) {
        number = number || 0;
        places = !isNaN(places = Math.abs(places)) ? places : 0;
        symbol = symbol !== undefined ? symbol : "¥";
        thousand = thousand || ",";
        decimal = decimal || ".";
        let negative = number < 0 ? "-" : "",
            i = parseInt(number = Math.abs(+number || 0).toFixed(places), 10) + "",
            j = (j = i.length) > 3 ? j % 3 : 0;
        return symbol + negative + (j ? i.substr(0, j) + thousand : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousand) + (places ? decimal + Math.abs(number - i).toFixed(places).slice(2) : "");
    }

    static parseOrderStatus(status,type = 1) {
        switch (status) {
            case 1:
                if(type == 1) {
                    return '待付定金';
                } else {
                    return '待付款';
                }
            case 2:
                return '受理中';
            case 3:
                return '待付尾款';
            case 4:
                return '已完成';


            case 6:
                return '已关闭';
            case 7:
                return '已取消';
            case 8:
                return '支付超时，系统取消';
            default:
                return '';
        }
    }

    static parseSexStatus( status) {
        switch (status) {
            case 1:
                return '未知';
            case 2:
                return '男';
            case 3:
                return '女';
            default:
                return '';
        }
    }

    static parseSaleStatus (status) {
        switch (status) {
            case 1:
                return '可售';
            case 2:
                return '锁定';
            case 3:
                return '已售';
            default:
                return '-';
        }
    }

    static renderComType = (type) => {
        switch (type) {
            case 1:
                return '中文';
            case 2:
                return '字母';
            case 8:
                return '数字';
            case 9:
                return '字母+数字';
            case 3:
                return '中文+字母';
            case 4:
                return '图形';
            case 5:
                return '中文+图形';
            case 6:
                return '字母+图形';
            case 7:
                return '中文+字母+图形';
            default:
                return '-';
        }
    };

    static parseDayHello () {
        let now = new Date(),hour = now.getHours();

        if(hour < 6){return("凌晨好!")}
        else if (hour < 9){return("早上好!")}
        else if (hour < 12){return("上午好!")}
        else if (hour < 14){return("中午好!")}
        else if (hour < 17){return("下午好!")}
        else if (hour < 19){return("傍晚好!")}
        else if (hour < 22){return("晚上好!")}
        else {return("夜里好!")}
    };

    static parseZeroValue = (val) => {
        if (parseInt(val) == 0 || !val) {
            return '-';
        } else {
            return val;
        }
    };

    static parseRegNo = (regNo = '') => {
        if (!regNo) return '';
        return CommonUtil.parseZeroValue(parseInt(regNo.replace(/[^0-9]/ig, "")) * 3);
    }
}
